//
//  NewUserViewController.m
//  ActiveDeck
//
//  Created by BigChicken on 4/10/11.
//  Copyright 2011 __MyCompanyName__. All rights reserved.
//

#import "NewUserViewController.h"
#import "GDataXMLNode.h"
#import "HttpRequest.h"

@implementation NewUserViewController

@synthesize Txt_FirstName, Txt_LastName , Txt_ConfimPass, Txt_Email, Txt_Password, Txt_Organization,createSuccess;
@synthesize Lb_ConfirmP, Lb_Email, Lb_FirstName, Lb_LastName, Lb_Org, Lb_Pass, Lb_Result, environment;

-(IBAction) CancelReg
{
    if([self respondsToSelector:@selector(presentingViewController)])
        [self.presentingViewController dismissModalViewControllerAnimated:YES];
    else
        [self.parentViewController dismissModalViewControllerAnimated:YES];
}



-(IBAction) SubmitReg
{
    if([self regValidation])
    {
        NSString *newUser = [self BuildXMLAuth];
        
        NSString *RegisterNewUser = [NSString stringWithFormat:@"%@/Config.svc/NewUser", [HttpRequest GetSvcURL]];
        
        HttpRequest *configRequest = [HttpRequest alloc];
        NSString *userXMLString = [configRequest XML_PostRequest:newUser urlString:RegisterNewUser];
        
        if([userXMLString isEqualToString:@"Error"])
        {
            UIAlertView *alertMSG = [UIAlertView alloc];
            alertMSG = [alertMSG initWithTitle:@"Username Taken"
                                       message:@"The Username you entered is already in use. Please enter a different one."
                                      delegate:self 
                             cancelButtonTitle:@"OK" 
                             otherButtonTitles:nil];
            
            [alertMSG show];
        }
        else
        {
            createSuccess = true;
            
            [environment setAuthenticationUsername:Txt_Email.text AndPassword:Txt_Password.text];            
            
            Txt_FirstName.text = @"";
            Txt_LastName.text = @"";
            Txt_Organization.text = @"";
            Txt_Email.text = @"";
            Txt_Password.text = @"";
            Txt_ConfimPass.text = @"";
            
            if([self respondsToSelector:@selector(presentingViewController)])
                [self.presentingViewController dismissModalViewControllerAnimated:YES];
            else
                [self.parentViewController dismissModalViewControllerAnimated:YES];
        }
    }
}

- (BOOL) regValidation
{
    BOOL check = true;
    

    
    if (![Txt_Password.text isEqualToString:Txt_ConfimPass.text])
    {
        check = false;
        Txt_Password.text = @"";
        Txt_ConfimPass.text = @"";
        Lb_Result.text = @"Passward does not match, please re-enter";
        Lb_ConfirmP.textColor = [UIColor orangeColor];
        Lb_Pass.textColor = [UIColor orangeColor];
    }
    
    if ([Txt_Password.text length] < 1)
    {
        Lb_ConfirmP.textColor = [UIColor orangeColor];
        Lb_Pass.textColor = [UIColor orangeColor];
        Lb_Result.text = @"Passward field cannot be blank";
    }
    
       
    if ([Txt_Organization.text length] < 1)
    {
        check = false;
        Lb_Result.text = @"Please enter name of Organization";
        Lb_Org.textColor = [UIColor orangeColor];;
    }
    
       
    if([Txt_LastName.text length] <1)
    {
        check = false;
        Lb_Result.text = @"Please enter LastName";
        Lb_LastName.textColor = [UIColor orangeColor];
    }
    
       
    if([Txt_FirstName.text length] < 1)
    {
        check = false;
        Lb_Result.text = @"Please enter FirstName";
        Lb_FirstName.textColor = [UIColor orangeColor];
    }
    
    if(![self validateEmail:Txt_Email.text])
    {
        check = false;
        Txt_Email.text = @"";
        Lb_Result.text = @"Please enter valid Email address";
        Lb_Email.textColor = [UIColor orangeColor];
    }
    
    return check;
}

- (BOOL) validateEmail: (NSString *) candidate {
    NSString *emailRegex = @"[A-Z0-9a-z._%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,4}"; 
    NSPredicate *emailTest = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", emailRegex]; 
    
    return [emailTest evaluateWithObject:candidate];
}

-(NSString *) BuildXMLAuth
{
	GDataXMLElement *Authentication = [GDataXMLNode elementWithName:@"Authentication"];
	GDataXMLNode *UserName = [GDataXMLNode attributeWithName:@"UserName" stringValue:Txt_Email.text];
    GDataXMLNode *Level = [GDataXMLNode attributeWithName:@"Level" stringValue:@"User"];
	GDataXMLNode *Password = [GDataXMLNode attributeWithName:@"Password" stringValue:Txt_Password.text];
    GDataXMLNode *FirstName = [GDataXMLNode attributeWithName:@"FirstName" stringValue:Txt_FirstName.text];
    GDataXMLNode *LastName = [GDataXMLNode attributeWithName:@"LastName" stringValue:Txt_LastName.text];
    GDataXMLNode *Organization = [GDataXMLNode attributeWithName:@"Organization" stringValue:Txt_Organization.text];
    
	[Authentication addChild:UserName];
	[Authentication addChild:Level];
    [Authentication addChild:Password];
    [Authentication addChild:FirstName];
    [Authentication addChild:LastName];
    [Authentication addChild:Organization];
	
	
	GDataXMLDocument *document = [[[GDataXMLDocument alloc] initWithRootElement:Authentication] autorelease];
	NSData	*xData = document.XMLData;
	NSString *createUserXML = [[NSString alloc] initWithData:xData encoding:NSUTF8StringEncoding];
	
    return createUserXML;
}


- (void)dealloc
{
    [super dealloc];
}

- (void)didReceiveMemoryWarning
{
    // Releases the view if it doesn't have a superview.
    [super didReceiveMemoryWarning];
    
    // Release any cached data, images, etc that aren't in use.
}

#pragma mark - View lifecycle

/*
// Implement loadView to create a view hierarchy programmatically, without using a nib.
- (void)loadView
{
}
*/


// Implement viewDidLoad to do additional setup after loading the view, typically from a nib.
- (void)viewDidLoad
{
    [super viewDidLoad];
    createSuccess = false;
    
    [Txt_Email setValue:[UIColor blackColor] 
             forKeyPath:@"_placeholderLabel.textColor"];
    [Txt_FirstName setValue:[UIColor blackColor] 
             forKeyPath:@"_placeholderLabel.textColor"];
    [Txt_LastName setValue:[UIColor blackColor] 
                 forKeyPath:@"_placeholderLabel.textColor"];
    [Txt_Organization setValue:[UIColor blackColor] 
                 forKeyPath:@"_placeholderLabel.textColor"];
}


- (void)viewDidUnload
{
    [super viewDidUnload];
    // Release any retained subviews of the main view.
    // e.g. self.myOutlet = nil;
}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    // Return YES for supported orientations
	return NO;
}

@end
